package com.ngkj.zmfptback.sys.service.write.impl;

import com.ngkj.zmfptback.sys.bean.UserEntity;
import com.ngkj.zmfptback.sys.mapper.read.UserReadMapper;
import com.ngkj.zmfptback.sys.mapper.read.UserRoleReadMapper;
import com.ngkj.zmfptback.sys.mapper.write.UserRoleWriteMapper;
import com.ngkj.zmfptback.sys.mapper.write.UserWriteMapper;
import com.ngkj.zmfptback.sys.service.write.UserWriteService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ChenHN
 * @since 2021/12/8 creation
 **/
@Service
@Transactional(propagation = Propagation.REQUIRED)
public class UserWriteServiceImpl implements UserWriteService {

    @Resource
    private UserWriteMapper userWriteMapper;

    @Resource
    private UserReadMapper userReadMapper;

    @Resource
    private UserRoleWriteMapper userRoleWriteMapperl;

    @Resource
    private UserRoleReadMapper userRoleReadMapper;

    @Override
    public boolean registerUser(UserEntity user) {
        UserEntity userByEmail = userReadMapper.getUserByEmail(user.getEmail());
        if (ObjectUtils.isEmpty(userByEmail)){
            userWriteMapper.registerUser(user);
            return true;
        }
        return false;
    }

    @Override
    public void updateLastLoginTime(UserEntity user) {
        userWriteMapper.updateUserLastLoginTime(user);
    }

    @Override
    public void editUserRole(Integer id, String rolesId) {
        String[] roles = rolesId.split(",");
        List<String> nowRoleIds = new ArrayList<>();
        for (String role : roles) {
            nowRoleIds.add(role);
        }
        List<String> interRoleIds = new ArrayList<>(nowRoleIds);
        List<String> roleIdsByUserId = userRoleReadMapper.getRoleIdsByUserId(id);
        //获取交集
        interRoleIds.retainAll(roleIdsByUserId);
        //新增
        nowRoleIds.removeAll(interRoleIds);
        if (nowRoleIds.size()>0){
            userRoleWriteMapperl.addUserRoles(id,nowRoleIds);
        }
        //删除
        roleIdsByUserId.removeAll(interRoleIds);
        if (roleIdsByUserId.size()>0){
            userRoleWriteMapperl.deleteUserRoles(id,roleIdsByUserId);
        }
    }

    @Override
    public void editHeadImage(String userId, String imagePath) {
        userWriteMapper.editHeadImage(userId,imagePath);
    }

    @Override
    public void updateRealId(Integer userId, Integer id) {
        userWriteMapper.updateRealId(userId,id);
    }

    @Override
    public void editNickname(Long id, String nickname) {
        userWriteMapper.editNickname(id,nickname);
    }


}
